const state = {
  conversionQueue: [],
  currentConversion: null,
  conversionHistory: [],
  conversionStats: {
    total: 0,
    success: 0,
    failed: 0,
    averageAccuracy: 0
  }
}

const mutations = {
  ADD_TO_QUEUE(state, template) {
    state.conversionQueue.push(template)
  },
  REMOVE_FROM_QUEUE(state, templateId) {
    const index = state.conversionQueue.findIndex(t => t.id === templateId)
    if (index !== -1) {
      state.conversionQueue.splice(index, 1)
    }
  },
  SET_CURRENT_CONVERSION(state, conversion) {
    state.currentConversion = conversion
  },
  ADD_TO_HISTORY(state, result) {
    state.conversionHistory.push(result)
    // 更新統計信息
    state.conversionStats.total++
    if (result.success) {
      state.conversionStats.success++
    } else {
      state.conversionStats.failed++
    }
    
    // 計算平均準確率
    const successfulConversions = state.conversionHistory.filter(r => r.success)
    if (successfulConversions.length > 0) {
      const totalAccuracy = successfulConversions.reduce((sum, r) => sum + r.accuracy, 0)
      state.conversionStats.averageAccuracy = totalAccuracy / successfulConversions.length
    }
  },
  UPDATE_CONVERSION_STATS(state, stats) {
    state.conversionStats = { ...state.conversionStats, ...stats }
  }
}

const actions = {
  async startBatchConversion({ commit, state }, templates) {
    // 批量轉換
    for (let template of templates) {
      commit('ADD_TO_QUEUE', template)
    }
    
    // 開始轉換
    while (state.conversionQueue.length > 0) {
      const template = state.conversionQueue[0]
      commit('SET_CURRENT_CONVERSION', template)
      
      try {
        const result = await performConversion(template)
        result.success = true
        commit('ADD_TO_HISTORY', result)
      } catch (error) {
        const result = {
          ...template,
          success: false,
          error: error.message,
          conversionTime: new Date().toISOString()
        }
        commit('ADD_TO_HISTORY', result)
      }
      
      commit('REMOVE_FROM_QUEUE', template.id)
    }
    
    commit('SET_CURRENT_CONVERSION', null)
  },
  
  async convertSingleTemplate({ commit }, template) {
    commit('SET_CURRENT_CONVERSION', template)
    
    try {
      const result = await performConversion(template)
      result.success = true
      commit('ADD_TO_HISTORY', result)
      return result
    } catch (error) {
      const result = {
        ...template,
        success: false,
        error: error.message,
        conversionTime: new Date().toISOString()
      }
      commit('ADD_TO_HISTORY', result)
      throw error
    } finally {
      commit('SET_CURRENT_CONVERSION', null)
    }
  }
}

const getters = {
  getQueueLength: (state) => state.conversionQueue.length,
  getCurrentConversion: (state) => state.currentConversion,
  getConversionHistory: (state) => state.conversionHistory,
  getConversionStats: (state) => state.conversionStats,
  getSuccessfulConversions: (state) => state.conversionHistory.filter(r => r.success),
  getFailedConversions: (state) => state.conversionHistory.filter(r => !r.success)
}

// 模擬轉換邏輯
async function performConversion(template) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      // 模擬轉換過程
      if (Math.random() > 0.1) { // 90%成功率
        const result = {
          ...template,
          id: Date.now(),
          originalContent: template.content,
          structuredContent: {
            title: extractTitle(template.content),
            parties: extractParties(template.content),
            caseType: extractCaseType(template.content),
            claims: extractClaims(template.content),
            keyPoints: extractKeyPoints(template.content)
          },
          accuracy: Math.random() * 0.3 + 0.7, // 70%-100%的準確率
          conversionTime: new Date().toISOString(),
          version: '1.1'
        }
        resolve(result)
      } else {
        reject(new Error('轉換失敗'))
      }
    }, 1000 + Math.random() * 2000) // 1-3秒隨機時間
  })
}

function extractTitle(content) {
  const lines = content.split('\n')
  for (let line of lines) {
    if (line.includes('判決書') || line.includes('裁定書') || line.includes('調解書')) {
      return line.trim()
    }
  }
  return '未知標題'
}

function extractParties(content) {
  const parties = []
  const lines = content.split('\n')
  for (let line of lines) {
    if (line.includes('原告') || line.includes('被告') || line.includes('上訴人') || line.includes('被上訴人')) {
      parties.push(line.trim())
    }
  }
  return parties
}

function extractCaseType(content) {
  const lines = content.split('\n')
  for (let line of lines) {
    if (line.includes('案由') || line.includes('糾紛')) {
      return line.trim()
    }
  }
  return '未知案由'
}

function extractClaims(content) {
  const claims = []
  const lines = content.split('\n')
  let inClaimsSection = false
  for (let line of lines) {
    if (line.includes('訴訟請求') || line.includes('請求')) {
      inClaimsSection = true
      continue
    }
    if (inClaimsSection && line.trim()) {
      claims.push(line.trim())
    }
  }
  return claims
}

function extractKeyPoints(content) {
  const keyPoints = []
  const lines = content.split('\n')
  let inKeyPointsSection = false
  for (let line of lines) {
    if (line.includes('裁判要點') || line.includes('本院認為')) {
      inKeyPointsSection = true
      continue
    }
    if (inKeyPointsSection && line.trim()) {
      keyPoints.push(line.trim())
    }
  }
  return keyPoints
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}